$(function () {
    view("$!curuser.unitid");

    $("#BtnAdd").bind('click', addOrganization);

    $("#BtnUpdate").bind('click',updateOrganization);

    $('#BtnDel').bind('click',deletOrganization);
});

var deletOrganization=function () {
    //根据id删除机构
    var unitId = $('#id').text();
    if(unitId==null){
        layer.msg('请选择要删除的机构！', {
            time: 1000, //10s后自动关闭
        });
        return;
    }
    layer.confirm('这是级联删除，下级机构及用户角色会被一起删除，您确认要删除吗？', {
        btn: ['删除','取消'] //按钮
    }, function(index,layero){
        $.ajax({
            url: base + "/private/sys/unit/del?id="+unitId,
            data: {},
            type: "POST",
            async: false,
            success: function (res) {
                layer.msg('已成功删除！', {
                    time: 1000, //20s后自动关闭
                });
                //TODO 需要联动树
                removeTreeNode(unitId);
            },
            fail: function (res) {
                layer.msg('系统错误！', {
                    icon: 5
                });
            }
        });
    });
}

var updateOrganization = function(){
    var data = getDataFromTable();
    if(data.id==""){
        layer.msg("请选择机构！", {
            time: 1000, //1s后自动关闭
        });
        return;
    }
        layui.use(['form', 'laytpl', 'laydate', 'laypage', 'layer'], function () {
            form = layui.form(),
                laytpl = layui.laytpl,
                layer = layui.layer;
            data = getDataFromTable();
            layerEditopen("organizationUpdateForm","编辑机构信息",data,contentEditDiv(data.id));
            initTopUnit(data);
        });
}

var getDataFromTable=function() {
    var unitId = $('#id').text();
    var unitName=$('#name').text();
    var unitCode = $('#unitcode').text();
    var telephone=$('#telephone').text();
    var address =$('#address').text();
    var email = $('#email').text();
    var website = $('#website').text();
    var descript= $('#descript').text();
    var data = {
        id: unitId,
        name: unitName,
        code: unitCode,
        phone: telephone,
        address: address,
        email: email,
        web: website,
        descript: descript
    };
    return data;
}


var addOrganization= function () {
    layui.use(['form', 'laytpl', 'laydate', 'laypage', 'layer'], function () {
        form = layui.form(),
            laytpl = layui.laytpl,
            layer = layui.layer;
        layeropen("organizationAddForm","增加机构信息",contentDiv());
        var unitId = $('#id').text();
        var unitName=$('#name').text();
        var data={id:unitId,name:unitName};
        initTopUnit(data);
    });
}

var layeropen=function (id,title,content) {
    layer.open({
        id:id
        ,type:1
        , title: title
        , content: content
        , area: ['800px', '650px']
        , btn: ['确认', '取消']
        , yes: function (index, layero) { //确认
            var data = $(layero).find("form").serializeJSON();
            //提交用户验证
            if(data.name == ""){
                var obj = $("input[name='name']");
                obj.focus();
                layer.tips('请填写此字段!', obj);
                return false;
            }
            $.ajax({
                url: base + "/private/sys/unit/addSave" ,
                data: data,
                async: false,
                success: function (res) {
                    // layer.msg("机构已新建成功！", {
                    //     time: 1000, //20s后自动关闭
                    // });
                    //TODO  新建成功以后tree需要全部展开并定位到新添加的treenode
                    layer.close(index);
                    view(res);//刷新表格
                    reloadTree(data.id);//树节点重新从该处展开
                },
                fail: function (res) {
                    layer.msg('系统错误！', {
                        icon: 5
                    });
                }
            });
        }
    });
}

var contentEditDiv = function (obj) {
    var content;
    var data = {
        "title": {
            "id":"机构编号",
            "name": "机构名称",
            "unitcode": "机构编码",
            "telephone": "联系电话",
            "address": "联系地址",
            "email": "电子邮件",
            "website": "网址",
            "descript": "机构描述"
        }, "text": {
            "id":obj.id,
            "name": "",
            "unitcode": "",
            "telephone": "",
            "address": "",
            "email": "",
            "website": "",
            "descript": ""
        }, "input": {
            "id":"hidden",
            "name": "textnotip",
            "unitcode": "textnotip",
            "telephone": "textnotip",
            "address": "textnotip",
            "email": "email",
            "website": "textnotip",
            "descript": "textnotip"
        }, "input_init": {}
    };
    var getDiv = "";
    if(dc_update.length>1){
        getDiv = dc_update[0].innerHTML;
    }else{
        getDiv = dc_update.innerHTML;
    }
    laytpl(getDiv).render(data, function (html) {
        content = html;
    });
    return content;
};


var layerEditopen=function (id,title,data,content) {
    layer.open({
        id:id
        ,type:1
        , title: title
        , content: content
        , area: ['800px', '650px']
        , btn: ['确认', '取消']
        , yes: function (index, layero) { //确认
            var data = $(layero).find("form").serializeJSON();
            //提交用户验证
            if(data.name == ""){
                var obj = $("input[name='name']");
                obj.focus();
                layer.tips('请填写此字段!', obj);
                return false;
            }

            $.ajax({
                url: base + "/private/sys/unit/updateSave" ,
                type:"post",
                data: data,
                async: false,
                success: function (res) {
                    layer.msg("机构信息已修改成功！", {
                        time: 1000, //20s后自动关闭
                    });
                    layer.close(index);
                    reloadCurrentNode(res,data.name);
                },
                fail: function (res) {
                    layer.msg('系统错误！', {
                        icon: 5
                    });
                }
            });
        },success:function () {
                bindDataToUpdateForm(data);
        }
    });
}

var bindDataToUpdateForm=function(data){
    if(data!=null){
        $("input[name='id']").attr("value",data.id);
        $("input[name='name']").attr("value",data.name);
        $("input[name='unitcode']").attr("value",data.code);
        $("input[name='telephone']").attr("value",data.phone);
        $("input[name='address']").attr("value",data.address);
        $("input[name='email']").attr("value",data.email);
        $("input[name='website']").attr("value",data.web);
        $("input[name='descript']").attr("value",data.descript);
    }
}

var initTopUnit = function(data){
        if (data != null) {
            $("#select").html("");
            var optionstring = "";
                if(data!=null){
                    optionstring += "<option value=\"" + data.id + "\" selected='selected'>" + data.name + "</option>";
                }
            $("#select").html('<option value="">无</option>' + optionstring);
        } else {
            $("#select").html('<option value="">无</option>');
        }
        form.render();
}

var contentDiv = function () {
    var content;
    var data = {
        "title": {
            "id": "上级机构",
            "name": "机构名称",
            "unitcode": "机构编码",
            "telephone": "联系电话",
            "address": "联系地址",
            "email": "电子邮件",
            "website": "网址",
            "descript": "机构描述"
        }, "text": {
            "id": "",
            "name": "",
            "unitcode": "",
            "telephone": "",
            "address": "",
            "email": "",
            "website": "",
            "descript": ""
        }, "input": {
            "id": "select",
            "name": "text",
            "unitcode": "text",
            "telephone": "text",
            "address": "text",
            "email": "text",
            "website": "text",
            "descript": "text"
        }, "input_init": {}
    };
    var getDiv = "";
    if(dc_update.length>1){
        getDiv = dc_update[0].innerHTML;
    }else{
        getDiv = dc_update.innerHTML;
    }
    laytpl(getDiv).render(data, function (html) {
        content = html;
    });
    return content;
};

var ztree;
var setting = {
    async : {
        enable : true,
        url : base+"/private/sys/unit/tree",
        autoParam : [ "id" ]
    },
    view : {
        nameIsHTML : true
    },
    callback : {
        onAsyncSuccess : zTreeOnAsyncSuccess
    }
};

function initTree(setting) {
    ztree = jQuery.fn.zTree.init(jQuery("#treeDemo"), setting);
}

function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
    //alert(treeId+":node:"+treeNode+msg);
    var tid = $("#id").html();
    ztree.selectNode(ztree.getNodeByParam("id", tid, null));
    if (tid != "") {
        ztree.expandNode(ztree.getNodeByParam("id", tid.substring(0,
            tid.length - 4), null), true,false,true);
    }
}


var tag = 1;
function view(id) {
    jQuery.ajax({
        url : base+"/private/sys/unit/view?id=" + id,
        success : function(res) {
                bindData("dg1",res);
            if (tag == 1) {
                            initTree(setting);
                            tag = 2;
            }
            return false;
        },
        fail : function(res) {
            alert("系统错误!");
        }
    });
}

//绑定数据到页面表单
var bindData = function(id, json ) {
    //清空ID容器下div块内容
    $('#'+id+' div').each(function(i){
        if ($(this).prop('tagName') == "DIV") {
            $(this).html("");
        } else {
            $(this).val("");
        }
    });
    //给div赋值

    var obj = json;

    $.each(obj, function(index, term) {
        var tid = index;
        if ($('#' + tid).prop('tagName') == "DIV") {
            $('#' + tid).html(term);
        } else {
            $('#' + tid).val(term);
        }
    });
};

//添加完成后展开到该节点
var  reloadTree=function (nodeId) {
    var node = ztree.getNodeByParam("id",nodeId);
    node.isParent=true;
    ztree.selectNode(node);//指定选中ID的节点
    ztree.reAsyncChildNodes(node, "refresh",false);
}

//编辑完成后更新节点名称,并选中节点
var reloadCurrentNode = function (nodeId,nodeName) {
    var node = ztree.getNodeByParam("id",nodeId);
    node.name=nodeName;
    ztree.updateNode(node);
    view(nodeId);
}

//删除完成后展开当前删除节点的父节点并选中.
var  removeTreeNode=function (nodeId) {
    var node = ztree.getNodeByParam("id",nodeId);
    var nodeParent = node.getParentNode();
    ztree.removeNode(node);
    ztree.selectNode(nodeParent);//指定选中ID的节点
    ztree.reAsyncChildNodes(nodeParent, "refresh",false);
    view(nodeParent);
}








